package document

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"time"

	"oa-rest/common"
	"oa-rest/config"

	"github.com/sirupsen/logrus"
)

// DocumentService 公文服务
type DocumentService struct {
	aiClient *common.Client
}

// NewDocumentService 创建公文服务
func NewDocumentService() *DocumentService {
	return &DocumentService{
		aiClient: common.AIHttpClient,
	}
}

// GetTemplates 获取公文模板列表
func (s *DocumentService) GetTemplates() ([]DocumentTemplate, error) {
	templates := []DocumentTemplate{
		{
			ID:          DocumentTypeNotice,
			Name:        "通知",
			Description: "发布指示、安排工作",
			Structure:   "标题+主送机关+正文+落款+日期",
			FormatRules: getNoticeFormatRules(),
		},
		{
			ID:          DocumentTypeCircular,
			Name:        "通报",
			Description: "表扬、批评、情况说明",
			Structure:   "标题+主送机关+正文+落款+日期",
			FormatRules: getCircularFormatRules(),
		},
		{
			ID:          DocumentTypeLetter,
			Name:        "函",
			Description: "商洽工作、询问答复",
			Structure:   "标题+主送机关+正文+落款+日期",
			FormatRules: getLetterFormatRules(),
		},
		{
			ID:          DocumentTypeReport,
			Name:        "报告",
			Description: "汇报工作、反映情况",
			Structure:   "标题+主送机关+正文+落款+日期",
			FormatRules: getReportFormatRules(),
		},
		{
			ID:          DocumentTypeRequest,
			Name:        "请示",
			Description: "请求指示、批准",
			Structure:   "标题+主送机关+正文+落款+日期",
			FormatRules: getRequestFormatRules(),
		},
		{
			ID:          DocumentTypeMinutes,
			Name:        "纪要",
			Description: "会议记录",
			Structure:   "标题+会议要素+正文+落款+日期",
			FormatRules: getMinutesFormatRules(),
		},
		{
			ID:          DocumentTypeDecision,
			Name:        "决定",
			Description: "决策事项",
			Structure:   "标题+主送机关+正文+落款+日期",
			FormatRules: getDecisionFormatRules(),
		},
		{
			ID:          DocumentTypeOpinion,
			Name:        "意见",
			Description: "建议性文件",
			Structure:   "标题+主送机关+正文+落款+日期",
			FormatRules: getOpinionFormatRules(),
		},
	}

	return templates, nil
}

// GenerateDocument 生成公文
func (s *DocumentService) GenerateDocument(req *GenerateDocumentRequest) (*GenerateDocumentResponse, error) {
	// 获取当前日期
	currentDate := time.Now().Format("2006年01月02日")

	// 调用AI服务生成内容
	aiReq := map[string]interface{}{
		"template_type": req.TemplateType,
		"title":         req.Title,
		"content":       req.Content,
	}

	var aiResp struct {
		Success    bool   `json:"success"`
		Content    string `json:"content"`
		RawContent string `json:"raw_content"`
		Error      string `json:"error"`
	}

	// 调试日志：输出实际请求的URL
	logrus.Debugf("AI服务请求URL: %s", config.AIUrl+":30023"+"/api/generate")

	err := s.aiClient.PostJSON(":30023/api/generate", aiReq, &aiResp)
	if err != nil {
		logrus.Errorf("AI服务调用失败: %v", err)
		return nil, fmt.Errorf("AI服务调用失败: %w", err)
	}

	// 检查AI服务返回的错误
	if aiResp.Error != "" {
		logrus.Errorf("AI服务返回错误: %s", aiResp.Error)
		return nil, fmt.Errorf("AI服务返回错误: %s", aiResp.Error)
	}

	// 优先使用AI服务返回的完整HTML内容（包含完整标题）
	htmlContent := aiResp.Content
	var rawContent string

	// 如果AI服务返回了HTML内容，直接使用它
	if htmlContent != "" {
		// rawContent使用AI服务返回的原始内容
		rawContent = aiResp.RawContent
		if rawContent == "" {
			// 如果没有raw_content，从HTML内容中提取文本
			rawContent = aiResp.Content
		}
	} else {
		// 如果AI服务没有返回HTML内容，则使用原始内容并格式化
		rawContent = aiResp.RawContent
		if rawContent == "" {
			rawContent = aiResp.Content
		}
		htmlContent = s.formatHTMLContent(rawContent, req)
	}

	return &GenerateDocumentResponse{
		Success:      true,
		Content:      htmlContent,
		RawContent:   rawContent,
		Date:         currentDate,
		TemplateType: req.TemplateType,
		Title:        req.Title,
	}, nil
}

// buildPrompt 构建AI提示词
func (s *DocumentService) buildPrompt(req *GenerateDocumentRequest) string {
	templateNames := map[int]string{
		DocumentTypeNotice:   "通知",
		DocumentTypeCircular: "通报",
		DocumentTypeLetter:   "函",
		DocumentTypeReport:   "报告",
		DocumentTypeRequest:  "请示",
		DocumentTypeMinutes:  "纪要",
		DocumentTypeDecision: "决定",
		DocumentTypeOpinion:  "意见",
	}

	templateName := templateNames[req.TemplateType]
	if templateName == "" {
		templateName = "公文"
	}

	prompt := fmt.Sprintf("请生成一份%s，标题为'%s'", templateName, req.Title)

	if req.Content != "" {
		prompt += fmt.Sprintf("，主要内容为：%s", req.Content)
	}

	// 添加格式要求
	prompt += "\n\n要求：\n"
	prompt += "1. 内容要符合正式公文写作规范\n"
	prompt += "2. 语言要庄重、准确、简洁\n"
	prompt += "3. 结构要完整，包含必要的公文要素\n"
	prompt += "4. 返回纯文本格式，不要包含HTML标签\n"

	return prompt
}

// formatHTMLContent 格式化HTML内容
func (s *DocumentService) formatHTMLContent(rawContent string, req *GenerateDocumentRequest) string {
	html := fmt.Sprintf(`<div style="font-family: 仿宋_GB2312, FangSong_GB2312, serif; font-size: 16pt; line-height: 28px;">
`)

	// 标题
	html += fmt.Sprintf(`<h1 style="font-family: 黑体; font-size: 22pt; text-align: center; font-weight: bold; margin: 1em 0;">%s</h1>
`, req.Title)

	// 正文内容
	lines := splitContentIntoLines(rawContent)
	for _, line := range lines {
		if line != "" {
			html += fmt.Sprintf(`<p style="text-indent: 2em; margin-bottom: 0.5em;">%s</p>
`, line)
		}
	}

	// 日期
	currentDate := time.Now().Format("2006年01月02日")
	html += fmt.Sprintf(`<p style="text-align: right; margin-top: 2em; margin-bottom: 0.5em;">%s</p>
`, currentDate)

	html += `</div>`

	return html
}

// splitContentIntoLines 将内容分割成行
func splitContentIntoLines(content string) []string {
	var lines []string
	current := ""

	for _, char := range content {
		if char == '\n' {
			if current != "" {
				lines = append(lines, current)
				current = ""
			}
		} else {
			current += string(char)
		}
	}

	if current != "" {
		lines = append(lines, current)
	}

	return lines
}

// 格式规则函数
func getNoticeFormatRules() FormatRules {
	return FormatRules{
		Title:       TextFormat{Font: "黑体", Size: "二号", Align: "center", Weight: "bold"},
		Body:        TextFormat{Font: "仿宋_GB2312", Size: "三号", Indent: "2字符", LineSpacing: "28磅"},
		Level1Title: TextFormat{Font: "黑体", Size: "三号", Weight: "bold"},
		Level2Title: TextFormat{Font: "楷体_GB2312", Size: "三号", Weight: "bold"},
		Signature:   TextFormat{Font: "仿宋_GB2312", Size: "三号", Align: "right"},
		Date:        TextFormat{Font: "仿宋_GB2312", Size: "三号", Align: "right"},
	}
}

func getCircularFormatRules() FormatRules {
	return getNoticeFormatRules() // 通报格式与通知相同
}

func getLetterFormatRules() FormatRules {
	return FormatRules{
		Title:       TextFormat{Font: "黑体", Size: "二号", Align: "center", Weight: "bold"},
		Body:        TextFormat{Font: "仿宋_GB2312", Size: "三号", Indent: "2字符", LineSpacing: "28磅"},
		Level1Title: TextFormat{Font: "黑体", Size: "三号", Weight: "bold"},
		Level2Title: TextFormat{Font: "楷体_GB2312", Size: "三号", Weight: "bold"},
		Signature:   TextFormat{Font: "仿宋_GB2312", Size: "三号", Align: "right"},
		Date:        TextFormat{Font: "仿宋_GB2312", Size: "三号", Align: "right"},
	}
}

func getReportFormatRules() FormatRules {
	return FormatRules{
		Title:       TextFormat{Font: "黑体", Size: "二号", Align: "center", Weight: "bold"},
		Body:        TextFormat{Font: "仿宋_GB2312", Size: "三号", Indent: "2字符", LineSpacing: "28磅"},
		Level1Title: TextFormat{Font: "黑体", Size: "三号", Weight: "bold"},
		Level2Title: TextFormat{Font: "楷体_GB2312", Size: "三号", Weight: "bold"},
		Signature:   TextFormat{Font: "仿宋_GB2312", Size: "三号", Align: "right"},
		Date:        TextFormat{Font: "仿宋_GB2312", Size: "三号", Align: "right"},
	}
}

func getRequestFormatRules() FormatRules {
	return getReportFormatRules() // 请示格式与报告相同
}

func getMinutesFormatRules() FormatRules {
	return FormatRules{
		Title:       TextFormat{Font: "黑体", Size: "二号", Align: "center", Weight: "bold"},
		Body:        TextFormat{Font: "仿宋_GB2312", Size: "三号", Indent: "2字符", LineSpacing: "28磅"},
		Level1Title: TextFormat{Font: "黑体", Size: "三号", Weight: "bold"},
		Level2Title: TextFormat{Font: "楷体_GB2312", Size: "三号", Weight: "bold"},
		Signature:   TextFormat{Font: "仿宋_GB2312", Size: "三号", Align: "right"},
		Date:        TextFormat{Font: "仿宋_GB2312", Size: "三号", Align: "right"},
	}
}

func getDecisionFormatRules() FormatRules {
	return FormatRules{
		Title:       TextFormat{Font: "黑体", Size: "二号", Align: "center", Weight: "bold"},
		Body:        TextFormat{Font: "仿宋_GB2312", Size: "三号", Indent: "2字符", LineSpacing: "28磅"},
		Level1Title: TextFormat{Font: "黑体", Size: "三号", Weight: "bold"},
		Level2Title: TextFormat{Font: "楷体_GB2312", Size: "三号", Weight: "bold"},
		Signature:   TextFormat{Font: "仿宋_GB2312", Size: "三号", Align: "right"},
		Date:        TextFormat{Font: "仿宋_GB2312", Size: "三号", Align: "right"},
	}
}

func getOpinionFormatRules() FormatRules {
	return FormatRules{
		Title:       TextFormat{Font: "黑体", Size: "二号", Align: "center", Weight: "bold"},
		Body:        TextFormat{Font: "仿宋_GB2312", Size: "三号", Indent: "2字符", LineSpacing: "28磅"},
		Level1Title: TextFormat{Font: "黑体", Size: "三号", Weight: "bold"},
		Level2Title: TextFormat{Font: "楷体_GB2312", Size: "三号", Weight: "bold"},
		Signature:   TextFormat{Font: "仿宋_GB2312", Size: "三号", Align: "right"},
		Date:        TextFormat{Font: "仿宋_GB2312", Size: "三号", Align: "right"},
	}
}

func (s *FileInfoHandler) RegisterRoutes(group *gin.RouterGroup) {
	fileInfoGroup := group.Group("/fileinfo")
	fileInfoGroup.POST("/create", s.CreateFileInfo)
	fileInfoGroup.GET("/get/:id", s.GetFileInfo)
	fileInfoGroup.PUT("/update", s.UpdateFileInfo)
	fileInfoGroup.DELETE("/delete/:id", s.DeleteFileInfo)
	fileInfoGroup.DELETE("/delete-by-name", s.DeleteFileInfoByName)
	fileInfoGroup.GET("/list", s.ListFileInfos)
}
